import React, { Component } from "react";
import { Card, Button, Table, Modal, message } from "antd";
// import { formateDate } from "../../utils/dateUtils";
import LinkButton from "../../components/link-button";
import { PAGE_SIZE } from "../../utils/constant";
import { reqUsers, reqDeleteUser, addorUpdateUser } from "../../api";
import UserForm from "./UserForm";
// 用户管理
export default class User extends Component {
  state = {
    users: [], //用户列表
    roles: [], //所有角色列表
    isShow: false, //是否显示模态框
  };

  //添加更新用户
  addOrUpdateUser = async () => {
    this.setState({
      isShow: false, //是否显示模态框
    });
    //收集数据
    const user = this.form.current.getFieldsValue();
    // console.log("1234567", user);
    this.form.current.resetFields();
    //如果是更新需要指定user的id属性
    if (this.user) {
      user.id = this.user.id;
    }
    //提交添加请求
    const result = await addorUpdateUser(user);
    //更新列表
    if (result.status === 200) {
      message.success(`${this.user ? "修改" : "添加"}用户成功`);
      this.getUsers();
    }
  };

  getUsers = async () => {
    const results = await reqUsers();
    console.log("yyyyyyyyy", results.data.users);
    // console.log(
    //   "hhhhhhhhh",
    //   results.data.roles.find((role) => role.id === "5fd06735fa244c0b10cadec7")
    // );

    if (results.status === 200) {
      const { users, roles } = results.data;
      this.initRoleNames(roles);
      this.setState({
        users,
        roles,
      });
    }
  };
  //显示添加页面
  showAdd = () => {
    this.user = null;
    this.setState({ isShow: true });
  };
  //显示修改页面
  showUpdate = (user) => {
    this.user = user; //保存user

    this.setState({ isShow: true });
  };
  //根据role的数组生成包含角色名的对象
  initRoleNames = (roles) => {
    const roleNames = roles.reduce((pre, role) => {
      pre[role.id] = role.name;
      return pre;
    }, {});
    //保存
    this.roleNames = roleNames;
  };

  initColumns = () => {
    this.columns = [
      {
        title: "用户名",
        dataIndex: "username",
        key: "username",
      },
      {
        title: "邮箱",
        dataIndex: "email",
        key: "email",
      },
      {
        title: "电话",
        dataIndex: "phone",
        key: "phone",
      },
      {
        title: "注册时间",
        dataIndex: "createTime",
        key: "createTime",
        //render: formateDate,
      },
      {
        title: "所属角色",
        dataIndex: "roleId",
        key: "roleId",
        render: (roleId) => this.roleNames[roleId],
        // this.state.roles.find((role) => role.id === roleId).name,
      },
      {
        width: 100,
        title: "操作",
        key: "",
        render: (users) => (
          <span>
            <LinkButton onClick={() => this.showUpdate(users)}>
              {/*//() => this.setState({ isShow: true }) */}
              修改
            </LinkButton>
            <LinkButton onClick={() => this.deleteUser(users)}>删除</LinkButton>
          </span>
        ),
      },
    ];
  };

  //删除指定用户
  deleteUser = (user) => {
    Modal.confirm({
      title: `是否删除用户${user.username}`,
      onOk: async () => {
        const results = await reqDeleteUser(user.id);
        if (results.status === 200) {
          message.success("删除成功");
          this.getUsers();
        }
      },
    });
  };
  componentWillMount() {
    this.initColumns();
  }

  //获取用户
  componentDidMount() {
    this.getUsers();
  }
  render() {
    const { users, isShow, roles } = this.state;
    const user = this.user || {};
    const title = (
      <Button type="primary" onClick={this.showAdd}>
        创建用户
      </Button>
    );

    return (
      <Card title={title}>
        <Table
          bordered
          dataSource={users}
          columns={this.columns}
          pagination={{ defaultPageSize: PAGE_SIZE, showQuickJumper: true }}
        />
        <Modal
          title={user.id ? "修改用户" : "添加用户"}
          visible={isShow}
          onOk={this.addOrUpdateUser}
          onCancel={() => (
            this.form.current.resetFields(), this.setState({ isShow: false })
          )}
        >
          <UserForm
            setForm={(form) => {
              this.form = form;
            }}
            roles={roles}
            user={user}
            roleNames={this.roleNames}
          />
        </Modal>
      </Card>
    );
  }
}
